package reviewJDBC;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-10-29
 * Time: 22:24
 */
public class Mysql {
    public static void main(String[] args) throws SQLException {
        //1.找到数据库
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/milk?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("");

        //2.建立连接
        Connection connection = dataSource.getConnection();
        //客户端输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入学号:");
        int id = scanner.nextInt();
        System.out.println("输入姓名:");
        String name = scanner.next();
        System.out.println("输入班级:");
        int classId = scanner.nextInt();

        //3.构造sql语句
        String sql = "insert into student values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        statement.setInt(3,classId);
        System.out.println(statement);
        //4.发送语句并接收响应
        int n = statement.executeUpdate();
        System.out.println(n);


        //5.关闭资源
        statement.close();
        connection.close();

    }
}
